package com.ruoyi.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description: CPU 密集型任务
 * @Author: hongyu.chen
 * @Date: 2025-03-06 11:58
 * @Version： 1.0
 **/
public class CpuIntensiveTaskThreadPool {
    public static void main(String[] args) {
        //获取 CPU 核心数
        int cpuCoreCount = Runtime.getRuntime().availableProcessors();
        //核心线程数
        int corePoolSize = cpuCoreCount * 2;
        //最大线程数
        int maximumPoolSize = corePoolSize * 8;
        long keepAliveTime = 60L;
        TimeUnit unit = TimeUnit.MILLISECONDS;
        //任务队列  有界队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1000);

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue
        );
        List<Integer> taskIds = new ArrayList<>();

        // 提交一千个任务
        for (int i = 0; i < 1000; i++) {
            final int taskId = i;
            executor.submit(() -> {
                // 模拟 CPU 密集型任务
                for (int j = 0; j < 1000000; j++) {
                    Math.sqrt(j);
                }
                System.out.println("Task " + taskId + " completed.");
                taskIds.add(taskId);
            });
        }
        System.out.println("taskIds: " + taskIds.size());

        executor.shutdown();
    }
}
